using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

using System.Text.Json;

using Tool;

namespace Abc.Application
{
    /// <summary>
    /// API 过滤器
    /// 需要注册 ：
    /// </summary>
    public class ApiActionFilterAttribute : ActionFilterAttribute
    {
        public ApiActionFilterAttribute()
        {
        }

        public override void OnResultExecuted(ResultExecutedContext context) => base.OnResultExecuted(context);

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var logcontent = "";
            // _logger.LogInformation(Newtonsoft.Json.JsonConvert.SerializeObject(actionContext.HttpContext.Request.Headers));

            //var par = actionContext.ActionArguments.ToList();
            //foreach (var item in actionContext.ActionArguments)
            //{
            //    var aa = System.Text.Json.JsonSerializer.Serialize(item.Value);
            //}

            logcontent = $"Path:{actionContext.HttpContext.Request.Path}";
            //var bb = System.Text.Json.JsonSerializer.Serialize(actionContext.ActionArguments, AppEx.GetDefaultJsonSerializerOptions());
            logcontent += $"\r\n参数:{JsonSerializer.Serialize(actionContext.ActionArguments, AppEx.GetDefaultJsonSerializerOptions)}";

            //var controller1 = actionContext.Controller.ToString();
            //var actionname = actionContext.ActionDescriptor.DisplayName;//Ocr.Application.Api.ApiAccountService.Login2 (Ocr.Application)
            //var a = actionContext.HttpContext.Request.Path;//{/api/account/login2}
            //var httpcontext = actionContext.HttpContext as Microsoft.AspNetCore.Http.HttpContext;
            var ipv4 = actionContext.HttpContext.GetRemoteIpAddressToIPv4();
            var ipv6 = actionContext.HttpContext.GetRemoteIpAddressToIPv6();

            logcontent += $"\r\nIPV4:{ipv4}    IPV6:{ipv6}";

            var area = actionContext.RouteData.Values["area"]?.ToString() ?? "";
            var controller = actionContext.RouteData.Values["controller"]?.ToString() ?? "";
            //var action = actionContext.RouteData.Values["action"]?.ToString() ?? "";

            var logFloderName = "Api";
            if (!string.IsNullOrWhiteSpace(area))
            {
                logFloderName = area;
            }
            if (!string.IsNullOrWhiteSpace(controller))
            {
                logFloderName += $"\\{controller}";
            }

            logFloderName = logFloderName.Trim('\\');
            //if (!string.IsNullOrWhiteSpace(area))
            //{
            //    logFloderName += $"\\{controller}";
            //}

            //var ip=actionContext.HttpContext.Request.HttpContext.
            AppEx.GetLogger(logFloderName: logFloderName).Debug(logcontent);
        }
    }
}